<?php
if (! defined('IN_WEB')) {
    exit('Access Denied');
}

class ImageAction {

    protected $imagesModel;

    function __construct () {
        $this->imagesModel = new DbKooltaoModel('kooltao_images');
    }

    function imageAdd($pid){
        if(!$_FILES) return;
        $_FILES['thumbnail'] && $this->imageDelByPid($_POST['pid'], 'thumbnail');
        $_FILES['image'] && $this->imageDelByPid($_POST['pid'], 'image');
        
        include(ROOT."/library/UploadFile.class.php");
        $UploadFile = new UploadFile(1024*1024*2, array('jpg', 'jpeg', 'gif', 'png'), '', 'data/upload/'.date('Y-m').'/', 'image_rename_rule');
        $UploadFile -> upload();
        $imageInfo = $UploadFile -> getUploadFileInfo();
        foreach($imageInfo as $info){
            $info['pid'] = $pid;
            $row = $this->imageDataRender($info);
            $data[] = $row;
        }
        $this->imagesModel->batchInsert($data);
        return $data;

    }
    
    function imageDataRender($info=array()){
        $path = trim($info['savepath'].$info['savename']);
        if($path && file_exists($path)){
            $imgData = getimagesize($path);
        }
        $data = array(
            'uid' => intval($_SESSION['uid']),
            'pid' => intval($info['pid']),
            'type' => trim($info['input_key']),
            'imagename' => $_FILES[$info['input_key']]['name'],
            'path' => $path,
            'filesize' => intval($info['size']),
            'width' => intval($imgData[0]),
            'height' => intval($imgData[1]),
            'created' => time(),
        );
        return $data;
    }
    
    function imageDelByPid($pid, $type=''){
        $where[] = array('pid', $pid);
        $type && $where[] = array('type', $type);
        $this->imagesModel->delete($where);
    }
}